﻿

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace TotalApplication.AngelSix
{
    /// <summary>
    /// Scroll an items control to the bottom when the datacontext changes
    /// </summary>
    public class ScrollToBottomOnLoadProperty : BaseAttachedProperty<ScrollToBottomOnLoadProperty, bool>
    {

        public override void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            // Don't do this in design time
            if (DesignerProperties.GetIsInDesignMode(sender)) return;

            if (sender is not ScrollViewer element) return;

            // Focus this control once loaded
            element.DataContextChanged -= Element_DataContextChanged;
            element.DataContextChanged += Element_DataContextChanged;
        }

        private void Element_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            // Scroll to bottom
            (sender as ScrollViewer)?.ScrollToBottom();
        }
    }

    /// <summary>
    /// Auto
    /// </summary>
    public class AutoScrollToBottomOnLoadProperty : BaseAttachedProperty<AutoScrollToBottomOnLoadProperty, bool>
    {

        public override void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            // Don't do this in design time
            if (DesignerProperties.GetIsInDesignMode(sender)) return;

            if (sender is not ScrollViewer element) return;

            // Focus this control once loaded
            element.ScrollChanged -= Element_ScrollChanged;
            element.ScrollChanged += Element_ScrollChanged;
        }

        private void Element_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            // Scroll to bottom
            // (sender as ScrollViewer)?.ScrollToBottom();

            var scroll = (ScrollViewer)sender;

            if(scroll.ScrollableHeight - scroll.VerticalOffset < 20)
                scroll.ScrollToEnd();

        }
    }
}
